package com.stxx.framwork.tran;

import cn.hutool.core.bean.BeanUtil;
import com.stxx.framwork.support.OptionInterface;
import java.util.*;

public class TranUtils {

    private Map<String,TranService> tranMap = new HashMap<>();
    public TranUtils add(String column,TranService tranService){
        tranMap.put(column,tranService);
        return this;
    }
    public TranUtils add(String column){
        tranMap.put(column,null);
        return this;
    }
    public void tran(Collection<? extends TranBean> list){
        if(list==null||list.isEmpty())return;
        Map<String, Set<String>> ids = new HashMap<>();
        list.forEach(item->{
            tranMap.forEach((key,value)->{
                Object value2 = BeanUtil.getFieldValue(item,key);
                if(value2==null)return;
                //如果是枚举，直接翻译
                if(value2 instanceof OptionInterface){
                    item.writeTranValue(key,((OptionInterface)value2).getLabel());
                    return;
                }
                if(!ids.containsKey(key)){
                    ids.put(key,new HashSet<>());
                }
                ids.get(key).add(value2.toString());
            });
        });
        ids.forEach((key,value)->{
            TranService tranService = tranMap.get(key);
            if(tranService==null)return;
            Map<String,Map<String,Object>> m = tranService.tran(key,value);
            if(m==null||m.isEmpty()){return;}
            list.forEach(item->{
                Object value3 = BeanUtil.getFieldValue(item,key);
                if(value3==null)return;
                if(m.containsKey(value3.toString())){
                    item.writeTranValue(m.get(value3.toString()));
                }
            });
        });
        this.tranMap =null;
    }
    public void tran(TranBean bean){
        this.tran(Arrays.asList(bean));
    }

    public static TranUtils build(){
        return new TranUtils();
    }
}
